﻿using InfluxDB.Client.Api.Domain;
using InfluxDB.Client;
using InfluxDB.Client.Writes;
using System;

namespace InfluxDB {
    public class InfluxDBTool {
        private  InfluxDBClient _client;
        private readonly string _org= "tzkj";
        private const string token = "rxgoRhdm0poBAjQqiGAsCQgchbNlBTZodqINAGM4JiZtw1dmigCYMy0bDqXd-atsQyhQe6XdoLBQXPTQot09vA==";
        public async Task<bool> InfluxDBConnectAsync() {
            try {
                _client = InfluxDBClientFactory.Create("http://192.168.7.81:8086", token);
                var orgs = await _client.GetOrganizationsApi().FindOrganizationsAsync(org: _org);
                var retention = new BucketRetentionRules(BucketRetentionRules.TypeEnum.Expire, 3600*24*31*365); //everySeconds：表示数据保留的时间间隔，以秒为单位。在这里设置为 3600，表示数据将在插入后的3600秒（1小时）后过期。
                if (orgs.Any()) {
                    // 如果存在组织信息，则连接成功
                    return true;
                }
                else {
                    // 连接成功，但未找到匹配的组织信息
                    return false;
                }
            }
            catch (Exception ex) {
                // 连接失败，可能出现异常
                Console.WriteLine($"连接失败: {ex.Message}");
                return false;
            }
        }


        public void Dispose() {
            _client.Dispose();
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public async Task InfluxDBWrite(PointData point) {
            const string bucket = "iot_bucket";
            if (_client != null) {
                using (var writeApi = _client.GetWriteApi()) 
                    {
                    //var point = PointData.Measurement("weatherstation")
                    //           .Tag("location", "San Francisco")
                    //           .Field("temperature", 25.5)
                    //           .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

                    writeApi.WritePoint(point, bucket, _org);
                }
            }
        }
    }

}